%%%-------------------------------------------------------------------
%%% @author root
%%% @copyright (C) 2016, <COMPANY>
%%% @doc
%%%
%%% @end
%%% Created : 14. 二月 2016 下午8:52
%%%-------------------------------------------------------------------
-module(cus_conversation_handler).
-behaviour(cowboy_http_handler).

-include("cus.hrl").

-export([init/3]).
-export([handle/2]).
-export([terminate/3]).




init(_Type, Req, _Opts) ->
  {ok, Req, undefined_state}.

handle(Req, State) ->
  {Method,_} = cowboy_req:method(Req),
  HasBody = cowboy_req:has_body(Req),
  {CookieVal, Req2} = cowboy_req:cookie(<<"sessionid">>, Req),
%%  check SessionID and refresh cookie
  case cus_util:filter(CookieVal) of
    {true,UserName, PassWord} ->
      SessionID = cus_util:get_session_id(UserName,PassWord),
      Req3 = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID, [
        {max_age, ?COOKIE_TIME}
      ], Req2),
      {ok,Req4} = maybe_echo(Method, HasBody, Req3),
      {ok, Req4, State};
    _->
      {ok, Body} = login_dtl:render([
      ]),
      {ok,Req3} = echo(Body, Req2),
      {ok, Req3, State}
  end.

terminate(_Reason, _Req, _State) ->
  ok.

maybe_echo(<<"GET">>, false, Req) ->
  {ok, Body} = cus_conversation_detail_dtl:render([

  ]),
  echo(Body, Req);

maybe_echo(<<"POST">>, true, Req) ->
  {ok, PostVals, Req2} = cowboy_req:body_qs(Req),
  Id = proplists:get_value(<<"id">>, PostVals),
  Info = cus_redis:get_conversation_info(Id),
  case Info of
    undefined->
      {ok, Body} = cus_conversation_detail_dtl:render([

      ]),
      echo(Body, Req2);
    _->
      {ok, Body} = cus_conversation_detail_plus_dtl:render([
        {cid,Info#cus_conversation.cid},
        {name,Info#cus_conversation.name},
        {members,?l2tuple(Info#cus_conversation.members)},
        {seq,Info#cus_conversation.seq},
        {status,Info#cus_conversation.status}
      ]),
      echo(Body, Req2)
  end;



maybe_echo(<<"POST">>, false, Req) ->
  {ok, Body} = failed_dtl:render([
    {errorMsg,"Missing body"}
  ]),
  cowboy_req:reply(400, [{<<"content-type">>, <<"text/html; charset=utf-8">>}], Body, Req);
maybe_echo(_, _, Req) ->

  {ok, Body} = failed_dtl:render([
    {errorMsg,"405"}
  ]),
  cowboy_req:reply(405, [{<<"content-type">>, <<"text/html; charset=utf-8">>}], Body, Req).


echo(undefined, Req) ->
  {ok, Body} = failed_dtl:render([
    {errorMsg,"system error"}
  ]),
  cowboy_req:reply(400, [{<<"content-type">>, <<"text/html; charset=utf-8">>}], Body, Req);

echo(Body, Req) ->
  cowboy_req:reply(200, [
    {<<"content-type">>, <<"text/html; charset=utf-8">>}
  ], Body, Req).

